package com.example.demo.service.impl;

import com.example.demo.dto.TaskTypeDTO;
import com.example.demo.entity.TaskType;
import com.example.demo.mapper.TaskTypeMapper;
import com.example.demo.service.TaskTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TaskTypeServiceImpl implements TaskTypeService {

    @Autowired
    private TaskTypeMapper taskTypeMapper;

    public TaskType createTaskType(TaskType taskType) {
        // 检查是否存在相同的数据源ID的记录
        if (existsByDataSourceId(taskType.getDataSourceId())) {
            throw new RuntimeException("数据源ID为 " + taskType.getDataSourceId() + " 的任务已存在");
        }
        
        taskType.setCreatedAt(LocalDateTime.now());
        taskType.setUpdatedAt(LocalDateTime.now());
        taskTypeMapper.insert(taskType);
        return taskType;
    }

    public boolean deleteTaskType(Long taskTypeId) {
        return taskTypeMapper.deleteById(taskTypeId) > 0;
    }

    public TaskType updateTaskType(TaskType taskType) {
        taskType.setUpdatedAt(LocalDateTime.now());
        taskTypeMapper.update(taskType);
        return taskType;
    }

    public TaskTypeDTO getTaskTypeById(Long taskTypeId) {
        TaskType taskType = taskTypeMapper.selectById(taskTypeId);
        return taskType != null ? TaskTypeDTO.fromEntity(taskType) : null;
    }

    public List<TaskTypeDTO> getAllTaskTypes() {
        List<TaskType> taskTypes = taskTypeMapper.selectAll();
        return taskTypes.stream()
                .map(TaskTypeDTO::fromEntity)
                .collect(Collectors.toList());
    }

    public List<TaskTypeDTO> getTaskTypesByDataSourceId(Long dataSourceId) {
        List<TaskType> taskTypes = taskTypeMapper.selectByDataSourceId(dataSourceId);
        return taskTypes.stream()
                .map(TaskTypeDTO::fromEntity)
                .collect(Collectors.toList());
    }

    public List<TaskTypeDTO> searchTaskTypesByName(String taskName) {
        List<TaskType> taskTypes = taskTypeMapper.selectByTaskName(taskName);
        return taskTypes.stream()
                .map(TaskTypeDTO::fromEntity)
                .collect(Collectors.toList());
    }

    public int countTaskTypes() {
        return taskTypeMapper.count();
    }
    
    public boolean existsByDataSourceId(Long dataSourceId) {
        List<TaskType> taskTypes = taskTypeMapper.selectByDataSourceIdOnly(dataSourceId);
        return taskTypes != null && !taskTypes.isEmpty();
    }
}